# -*- coding: utf-8 -*-
# @version : 1.0
# @File    : login_manage.py
# @Date    : 2024/9/27 14:09
# @Author  : GlenZhao
# @Desc    :
import jwt
import json
from datetime import timedelta, datetime

from application import settings
from apps.auth.user.models import AuthUser
from apps.auth.user.schemas import UserCache
from core.redis import RedisManager


class LoginManage:
    """
    登录认证工具
    """

    @staticmethod
    def create_token(payload: dict, expires: timedelta = None):
        """
        创建一个生成新的访问令牌的工具函数。

        pyjwt：https://github.com/jpadilla/pyjwt/blob/master/docs/usage.rst
        jwt 博客：https://geek-docs.com/python/python-tutorial/j_python-jwt.html

        #TODO 传入的时间为UTC时间datetime.datetime类型，但是在解码时获取到的是本机时间的时间戳
        """
        if expires:
            expire = datetime.utcnow() + expires
        else:
            expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        payload.update({"exp": expire})
        encoded_jwt = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
        return encoded_jwt

    @staticmethod
    def gen_token_key(key) -> str:
        return f'token-{key}'

    @staticmethod
    def gen_user_key(key) -> str:
        return f'user-{key}'

    @staticmethod
    async def cache_token(token: str, key: str):
        """
        缓存token
        """
        await RedisManager().set(LoginManage.gen_token_key(key), token, ex=settings.UNI_TOKEN_EXPIRES_IN)

    @staticmethod
    async def cache_userinfo(user:AuthUser) -> UserCache:
        """
        缓存user信息
        """
        user_cache = UserCache.model_validate(user)
        await RedisManager().set(LoginManage.gen_user_key(user.id), json.dumps(user_cache.model_dump()))
        return user_cache

    @staticmethod
    async def get_cache_userinfo(user_id):
        return await RedisManager().get(LoginManage.gen_user_key(user_id))